package com.macro.mall.service.impl;

import cn.hutool.core.util.StrUtil;
import com.github.pagehelper.PageHelper;
import com.macro.mall.common.api.CommonResult;
import com.macro.mall.common.api.IErrorCode;
import com.macro.mall.common.api.ResultCode;
import com.macro.mall.common.exception.Asserts;
import com.macro.mall.common.utils.Assist;
import com.macro.mall.mapper.TiTrainingMapper;
import com.macro.mall.mapper.TiTrainingSignRecordLogMapper;
import com.macro.mall.mapper.TiTrainingSignRecordMapper;
import com.macro.mall.model.*;
import com.macro.mall.service.TiTrainingSignService;
import com.macro.mall.utils.Mapping;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * TiTrainingSign的服务接口的实现类
 *
 * @author
 */
@Slf4j
@Service
public class TiTrainingSignServiceImpl implements TiTrainingSignService {

    private boolean isDebugEnabled = true;

    @Autowired
    private TiTrainingMapper tiTrainingMapper;
    @Autowired
    private TiTrainingSignRecordMapper tiTrainingSignRecordMapper;
    @Autowired
    private TiTrainingSignRecordLogMapper tiTrainingSignRecordLogMapper;

    @Override
    public List<TiTrainingSignRecordLog> find(String courseName,String communityName,String phone,String userIdentity,String signStatus,Integer pageNum,Integer pageSize) {
        //TODO这里可以做通过Assist做添加查询
        PageHelper.startPage(pageNum, pageSize);
        Assist assist = new Assist();
        List<TiTrainingSignRecordLog> result = null;
        try {
            if (StrUtil.isNotEmpty(courseName)) {
                assist.andLike("course_name", "%" + courseName +"%");
            }
            if (StrUtil.isNotEmpty(communityName)) {
                assist.andLike("community_name", "%" + communityName +"%");
            }
            if (StrUtil.isNotEmpty(phone)) {
                assist.andLike("phone", "%" + phone +"%");
            }
            if (StrUtil.isNotEmpty(userIdentity)) {
                assist.andLike("user_identity", "%" + userIdentity +"%");
            }
            if (StrUtil.isNotEmpty(signStatus)) {
                assist.andEq("sign_status", signStatus);
                if ("01".equals(signStatus)) {
                    assist.orEq("sign_status", "02");
                }
            }else {
                assist.andNeq("sign_status", "null");
            }
            assist.setOrder(Assist.order("create_time",false));
            result = tiTrainingSignRecordLogMapper.selectTiTrainingSignRecordLog(assist);
            result.stream().forEach(r->{
                r.setUserIdentityName(Mapping.getSplitName(r.getUserIdentity()));
            });
        } catch (Exception e) {
            log.error("", e);
            Asserts.fail(ResultCode.FAILED);
        }
        if (isDebugEnabled) {
            log.debug("执行获取TiTrainingSignRecordLog数据集-->结果:{}", result);
        }
        return result;
    }

    @Override
    public TiTrainingSignRecordLog findOne(Integer id) {
        if (id == null) {
            if (isDebugEnabled) {
                log.debug("执行通过TiTrainingSignRecordLog的id获得TiTraining对象-->失败:id不能为空");
            }
            Asserts.fail("执行通过TiTrainingSignRecordLog的id获得TiTraining对象-->失败:id不能为空");
        }
        TiTrainingSignRecordLog result = null;
        try {
            result = tiTrainingSignRecordLogMapper.selectTiTrainingSignRecordLogById(id);
        } catch (Exception e) {
            log.error("", e);
            Asserts.fail(ResultCode.FAILED);
        }
        if (isDebugEnabled) {
            log.debug("执行通过TiTrainingSignRecordLog的id获得TiTraining对象-->结果:{}", result);
        }
        return result;
    }

    @Override
    public CommonResult saveNotNull(TiTrainingSignRecordLog value) {
        if (value == null) {
            if (isDebugEnabled) {
                log.debug("执行将TiTrainingSignRecordLog中属性值不为null的数据保存到数据库-->失败:对象不能为空");
            }
            Asserts.fail("失败:对象不能为空");
        }
        int result = 0;
        try {
            value.setCreateTime(new Date());
            result = tiTrainingSignRecordLogMapper.insertNotNullTiTrainingSignRecordLog(value);
        } catch (Exception e) {
            log.error("", e);
            Asserts.fail(ResultCode.FAILED);
        }
        if (isDebugEnabled) {
            log.debug("执行将TiTrainingSignRecordLog中属性值不为null的数据保存到数据库-->结果:{}", result);
        }
        return CommonResult.success(null);
    }

    @Override
    public CommonResult updateNotNullById(TiTrainingSignRecordLog value) {
        if (value == null) {
            if (isDebugEnabled) {
                log.debug("执行通过TiTrainingSignRecordLog的id更新TiTrainingSignRecordLog中属性不为null的数据-->失败:对象为null");
            }
            Asserts.fail("执行通过TiTrainingSignRecordLog的id更新TiTrainingSignRecordLog中属性不为null的数据-->失败:对象为null");
        }
        int result = 0;
        try {
            value.setUpdateTime(new Date());
            result = tiTrainingSignRecordLogMapper.updateNotNullTiTrainingSignRecordLogById(value);
        } catch (Exception e) {
            log.error("", e);
            Asserts.fail(ResultCode.FAILED);
        }
        if (isDebugEnabled) {
            log.debug("执行通过TiTrainingSignRecordLog的id更新TiTrainingSignRecordLog中属性不为null的数据-->结果:{}", result);
        }
        return CommonResult.success(null);
    }


    @Override
    public CommonResult signConfig(TiTrainingSignRecordLog request,String oper) {
        if (request == null) {
            if (isDebugEnabled) {
                log.debug("执行通过TiTrainingSignRecordLog请求操作数据库-->失败:对象为null");
            }
            Asserts.fail("执行通过TiTrainingSignRecordLog请求操作数据库-->失败:对象为null");
        }
        Date currentTime = new Date();
        if (StrUtil.isEmpty(request.getPhone())){
            CommonResult.failed(ResultCode.VALIDATE_FAILED,"手机号码不可为空");
        }
        int result = 0;
        try {
            switch (oper){
                case "01":
                    TiTrainingSignRecordLog srlSignOutCheck = tiTrainingSignRecordLogMapper.selectTiTrainingSignRecordLogSingle(request);
                    if (!StringUtils.isEmpty(srlSignOutCheck)&&!StringUtils.isEmpty(srlSignOutCheck.getSignStatus())) {
                        CommonResult.failed(ResultCode.VALIDATE_FAILED,"无需重复签到");
                    }
                    TiTraining tiTraining = tiTrainingMapper.selectTiTrainingById(request.getTrainingId());
                    if (!StringUtils.isEmpty(tiTraining)) {
                        List<TiTrainingSignRecord> srSignInList = tiTraining.getSignList().stream().filter(tts ->
                                tts.getSignInStartTime().before(currentTime) && tts.getSignInEndTime().after(currentTime)
                        ).sorted(Comparator.comparing(TiTrainingSignRecord::getId)).collect(Collectors.toList());
                        //可以簽到
                        if (!CollectionUtils.isEmpty(srSignInList)) {
                            request.setSignRecordId(srSignInList.get(0).getId());
                            request.setSignStatus("01");
                            request.setSignInTime(currentTime);
                            if(!StringUtils.isEmpty(srlSignOutCheck)) {
                                request.setId(srlSignOutCheck.getId());
                                request.setUpdateTime(currentTime);
                                result = tiTrainingSignRecordLogMapper.updateNotNullTiTrainingSignRecordLogById(request);
                            }else {
                                request.setCreateTime(currentTime);
                                result = tiTrainingSignRecordLogMapper.insertNotNullTiTrainingSignRecordLog(request);
                            }
                        } else {
                            CommonResult.failed(ResultCode.VALIDATE_FAILED,"不在签到时间区间");
                        }
                    }
                    break;
                case "02":
                    TiTrainingSignRecordLog srlSignOut = tiTrainingSignRecordLogMapper.selectTiTrainingSignRecordLogSingle(request);
                    if (!StringUtils.isEmpty(srlSignOut)&&!StringUtils.isEmpty(srlSignOut.getSignStatus())) {
                        if ("01".equals(srlSignOut.getSignStatus())) {
                            //可以簽退
                            TiTrainingSignRecord ttsr = tiTrainingSignRecordMapper.selectTiTrainingSignRecordById(srlSignOut.getSignRecordId());
                            if (!StringUtils.isEmpty(ttsr)) {
                                //可以簽退
                                if (ttsr.getSignOutStartTime().before(currentTime) && ttsr.getSignOutEndTime().after(currentTime)) {
                                    request.setId(srlSignOut.getId());
                                    request.setSignStatus("02");
                                    request.setSignOutTime(currentTime);
                                    request.setUpdateTime(currentTime);
                                    tiTrainingSignRecordLogMapper.updateNotNullTiTrainingSignRecordLogById(request);
                                } else {
                                    CommonResult.failed(ResultCode.VALIDATE_FAILED,"不在签退时间区间");
                                }
                            }
                        } else {
                            CommonResult.failed(ResultCode.VALIDATE_FAILED, "请勿重复签退");
                        }
                    } else {
                        CommonResult.failed(ResultCode.VALIDATE_FAILED,"请先签到");
                    }
                    break;
                default:
                    break;
            }
        } catch (Exception e) {
            log.error("", e);
            Asserts.fail(ResultCode.FAILED);
        }
        if (isDebugEnabled) {
            log.debug("执行通过TiTrainingSignRecord请求操作数据库-->结果:{}",result);
        }
        return CommonResult.success(null);
    }


    @Override
    public CommonResult deleteById(Integer id) {
        if (id == null) {
            if (isDebugEnabled) {
                log.debug("执行通过TiTrainingSignRecordLog的id删除TiTraining-->失败:id不能为空");
            }
            Asserts.fail("执行通过TiTrainingSignRecordLog的id删除TiTraining-->失败:id不能为空");
        }
        int result = 0;
        try {
            result = tiTrainingSignRecordLogMapper.deleteTiTrainingSignRecordLogById(id);
        } catch (Exception e) {
            log.error("", e);
            Asserts.fail(ResultCode.FAILED);
        }
        if (isDebugEnabled) {
            log.debug("执行通过TiTrainingSignRecordLog的id删除TiTraining-->结果:{}", result);
        }
        return CommonResult.success(null);
    }

}
